package baibeiwallet.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.web3j.crypto.Keys;

import java.math.BigDecimal;
import java.math.BigInteger;

import baibeiwallet.BaibeiWallet;
import baibeiwallet.ClipboardUtils;
import baibeiwallet.WalletDaoUtils;
import baibeiwallet.WalletManager;
import baibeiwallet.event.CreateWalletEvent;
import baibeiwallet.event.SelWalletEvent;
import baibeiwallet.model.ETHWallet3;
import baibeiwallet.model.TokenModel;
import baibeiwallet.solidity.Token;
import baibeiwallet.utils.BaibeiTransferUtils;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;

public class WalletDetailActivity1 extends BaseActivity {
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.tv_address)
    TextView mTvAddress;

    @BindView(R.id.tv_balance_eth)
    TextView mTvBalanceEth;
    @BindView(R.id.tv_balance_token)
    TextView mTvBalanceToken;

    BaibeiWallet mWallet;
    String baibeiWalletAdress = "";
    Token mContract;
    int index;
    @BindView(R.id.btn_selectwallet)
    Button btnSelectwallet;
    public static final int ITEM_requestcode = 11, ITEM_clearwallet_resultcode = 111;
    private String pwd = "";

    @Override
    protected MyPreenter initPreenter() {
        return null;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_wallet_detail3;
    }

    @Override
    protected void initVariables() {
        new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item22));
        index = getIntent().getIntExtra("index", 0);
        mWallet = WalletManager.getInstance().getWallet(index);
        new ActionBarHelper(this).setTitle(mWallet.getWalletName());
        baibeiWalletAdress = Keys.toChecksumAddress(mWallet.getWalletFile().getAddress());
    }

    @Override
    protected void initViews() {
        mTvAddress.setText(baibeiWalletAdress);
//        mTvName.setText(mWallet.getWalletName());
    }

    @Override
    protected void loadData() {
//        Log.e("999999999", "刷新钱包1");
//        if (mWallet == null) {
//            showToast("钱包为空!");
////            Toast.makeText(this, "钱包为空", Toast.LENGTH_SHORT).show();
//        } else {
//            getBalanceForETH(baibeiWalletAdress);
//        }
//        loadContract(Constant.G12ContractAddress, Constant.G12ContractName);
    }


    private void getBalanceForETH(String addr) {
        BaibeiTransferUtils.getBalanceForETH(addr)
                .subscribe(new SingleObserver<BigInteger>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onSuccess(BigInteger bigInteger) {
                        BigDecimal bigDecimal = new BigDecimal(bigInteger + ".0000");
                        BigDecimal bigDecimal1 = new BigDecimal("1000000000000000000.0000");
                        LogUtil.d( "余额：" + bigDecimal.divide(bigDecimal1, BigDecimal.ROUND_HALF_UP));
//                        Toast.makeText(WalletDetailActivity1.this, "ETH余额：" + bigDecimal.divide(bigDecimal1, BigDecimal.ROUND_HALF_UP), Toast.LENGTH_SHORT).show();
                        if (mTvBalanceEth != null) {
                            mTvBalanceEth.setText("" + bigDecimal.divide(bigDecimal1, BigDecimal.ROUND_HALF_UP));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.d("余额查询有误！" + e.getMessage());
                        if (mTvBalanceEth != null)
                            mTvBalanceEth.setText(getString(R.string.wallet_hint_warn6) + e.getMessage());
                    }
                });
    }

    private void loadContract(String contractAddr, String tokenName) {
        TokenModel mTokenModel = new TokenModel(contractAddr, tokenName, false);
        if (mTokenModel != null && mTokenModel.isEth) {
            //以太坊不需要加载合约
            return;
        }
        BaibeiTransferUtils.loadContract(mWallet, mTokenModel.getAddr(), getGasPrice(), getGasLimit())
                .subscribe(new SingleObserver<Token>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onSuccess(Token token) {
//                        Toast.makeText(WalletDetailActivity1.this, "合约加载完成！", Toast.LENGTH_SHORT).show();
                        mContract = token;
                        getBalance(tokenName);
                    }

                    @Override
                    public void onError(Throwable e) {
//                        showToast("合约加载失败!");
//                        Toast.makeText(WalletDetailActivity1.this, "合约加载失败！", Toast.LENGTH_SHORT).show();
                        showToast(getString(R.string.common_loaderrritry));

                    }
                });
    }

    private void getBalance(String tokenName) {
        if (mContract == null) {
            Toast.makeText(WalletDetailActivity1.this, getString(R.string.profile_hint_item7), Toast.LENGTH_SHORT).show();
            return;
        }

        BaibeiTransferUtils.balanceOf(mContract, mWallet.getWalletFile().getAddress())
                .subscribe(mBalanceObserver);

    }


    private SingleObserver<BigInteger> mBalanceObserver = new SingleObserver<BigInteger>() {
        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onSuccess(BigInteger bigInteger) {
//            Toast.makeText(WalletDetailActivity1.this, "代币余额：" + bigInteger.toString(), Toast.LENGTH_SHORT).show();
            if (mTvBalanceToken != null)
                mTvBalanceToken.setText(bigInteger.toString());
        }

        @Override
        public void onError(Throwable e) {
            LogUtil.d( "代币余额查询有误！" + e.getMessage());
            if (mTvBalanceToken != null)
                mTvBalanceToken.setText(getString(R.string.wallet_hint_warn6) + e.getMessage());
        }
    };

    private BigInteger getGasPrice() {
        return BigInteger.valueOf(1000);
    }

    private BigInteger getGasLimit() {
        return BigInteger.valueOf(600000);
    }

    @OnClick(R.id.btn_beifen)
    public void onClickCopy() {
        if (TextUtils.isEmpty(mTvAddress.getText().toString())) {
//            Toast.makeText(this, "钱包地址为空", Toast.LENGTH_SHORT).show();
            showToast(getString(R.string.wallet_hint_warn5));
            return;
        }
        Intent i = new Intent(WalletDetailActivity1.this, WalletSettingActivity1.class);
        i.putExtra("index", index);
        startActivity(i);
    }

    @OnClick(R.id.btn_copy_address)
    public void onClickCopyAddress() {
        String address = mTvAddress.getText().toString();
        if (TextUtils.isEmpty(address)) {
//            Toast.makeText(this, "地址为空", Toast.LENGTH_SHORT).show();
            showToast(getString(R.string.wallet_hint_warn5));
            return;
        }

        ClipboardUtils.copy(address);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCreateWalletEvent(CreateWalletEvent cwe) {
//        if (cwe.index == -1) {//本页面刷新
//            mAdapter.setData(false);
//        } else
//            mAdapter.setData(true);
    }

    @OnClick(R.id.btn_selectwallet)
    public void onViewClicked() {
        EventBus.getDefault().post(new SelWalletEvent(index, "sellectwallet"));
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.rly_beifenmonic_item, R.id.rly_expprivkey_item, R.id.rly_expkeystore_item})
    public void onViewClicked(View view) {
        if (TextUtils.isEmpty(mTvAddress.getText().toString())) {
            showToast(getString(R.string.wallet_hint_warn5));
            return;
        }
        Intent i = new Intent(WalletDetailActivity1.this, WalletSettingActivity1.class);
        i.putExtra("index", index);
        switch (view.getId()) {
            case R.id.rly_beifenmonic_item:
                i.putExtra("itemNum", WalletSettingActivity1.ITEM_beifenmonic);
                break;
            case R.id.rly_expprivkey_item:
                i.putExtra("itemNum", WalletSettingActivity1.ITEM_expprivkey);
                break;
            case R.id.rly_expkeystore_item:
                i.putExtra("itemNum", WalletSettingActivity1.ITEM_expkeystore);
                break;
        }
        startActivityForResult(i, ITEM_requestcode);
    }


    @OnClick({R.id.rly_walletname_item, R.id.rly_clearwallet_item})
    public void onViewClicked1(View view) {
        if (TextUtils.isEmpty(mTvAddress.getText().toString())) {
            showToast(getString(R.string.wallet_hint_warn5));
            return;
        }

        switch (view.getId()) {
            case R.id.rly_walletname_item:
                DialogUtils.enterPwd2(WalletDetailActivity1.this, mWallet, (pwd) -> {
                    for (ETHWallet3 ethWallet : WalletDaoUtils.loadAll()) {
                        if (ethWallet.getAddress().equalsIgnoreCase(Keys.toChecksumAddress(mWallet.getWalletFile().getAddress()))) {
                            WalletDaoUtils.updateWalletName(ethWallet.getId(),pwd);
                            mWallet.setWalletName(pwd);
                            if (WalletManager.getInstance().update(index, mWallet))
                                showToast(getString(R.string.wallet_hint_warn8));
                            new ActionBarHelper(this).setTitle(mWallet.getWalletName());
//                            EventBus.getDefault().post(new CreateWalletEvent(-1));
                            EventBus.getDefault().post(new SelWalletEvent(-1, "sellectwallet"));
                            break;
                        }
                    }

                });
                break;
            case R.id.rly_clearwallet_item:
                UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                sysMsgBean.setTitle(getString(R.string.wallet_hint_warn9));
                sysMsgBean.setContent(getString(R.string.wallet_hint_warn10));
                DialogUtils.showInfor1(WalletDetailActivity1.this, sysMsgBean, (pwd) -> {
                    showenterPwd();
                });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


//        if(requestCode==ITEM_requestcode&&resultCode){
//
//        }


    }

    protected void showenterPwd() {
        DialogUtils.enterPwd1(WalletDetailActivity1.this, (pwd1) -> {
            for (ETHWallet3 ethWallet : WalletDaoUtils.loadAll()) {
                if (ethWallet.getAddress().equalsIgnoreCase(Keys.toChecksumAddress(mWallet.getWalletFile().getAddress()))) {
                    if (pwd1 != null && pwd1.equalsIgnoreCase(ethWallet.getPassword())) {

                        WalletDaoUtils.deleteWallet(ethWallet.getId());
                        if (WalletManager.getInstance().remove(index, mWallet)) {
                            showToast(getString(R.string.wallet_hint_warn11));
                            if (WalletManager.getInstance().getWalletAll().size() != 0) {
                                EventBus.getDefault().post(new SelWalletEvent(0, "sellectwallet"));
                            } else {
//                                startActivity(MainActivity.class);
                                EventBus.getDefault().post(new SelWalletEvent(0, "sellectwallet"));
                            }
                            finish();
                        }
                    } else {
                        showToast(getString(R.string.wallet_hint_warn12));
                    }
                    break;
                }
            }
        });


    }


}
